<?php

namespace app\api\controller\verificat;

use addons\shopro\model\OrderItem;
use addons\shopro\model\Store;
use addons\shopro\model\User;
use app\common\controller\Verifcat;
use app\api\model\wanlshop\Goods;
use app\api\model\wanlshop\Order as OderModel;
use app\common\helpers\ImageUtil;
use think\Exception;
use think\Db;
use think\Log;

class Order extends Verifcat
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    public function index()
    {
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',10);//每页展示数量
        $search = $this->request->param('search');//搜索
        $where=[
            'o.type'=>['in',['information','subject','project']],
            'o.state'=>'6',
            'o.shop_id'=>$this->auth->shop_id,
        ];
        $wheres =[];
        if($search){
            $wheres[implode("|",['shopname','su.username','sg.title'])]= ["LIKE", "%{$search}%"];
        }
        
        $model =(new \app\admin\model\wanlshop\Order)
            ->alias('o')
            ->field('o.id,shopname,sg.title,actual_payment,order_no,paymenttime,o.createtime,su.username,verify_time')
            ->join('wanlshop_shop_user su','su.id=o.verify_user_id','left')
            ->join('wanlshop_shop s','s.id = o.shop_id','left')
            ->join('wanlshop_order_goods sg','sg.order_id = o.id','left')
            ->order('o.createtime desc')
            ->where($where)
            ->where($wheres)
            ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);

        $total= $model->total();
        $list =  $model->items();

        foreach($list as $v){
            $v->unsetAppend();
        }
        $result = array("total" =>$total , "list" => $list);
        $this->success("核销记录",$result);
    }
    
    public function confirm()
    {
        repeat_filter();        // 防抖
        $params = $this->request->post();
        $user = $this->auth->getUserinfo();
        extract($params);
        $id = $params['id'] ?? 0;
        $codes = urldecode($params['codes'] ?? '');
        Db::transaction(function () use ($user, $codes,$id) {

            $order =  (new \app\api\model\wanlshop\Order())
                ->where('id',$id)
                ->where('verify_code',$codes)
                ->find();
            $goods =  (new \app\api\model\wanlshop\OrderGoods())
                ->where('order_id',$id)
                ->find();
            if (!$order) {
                $this->error('核销码不可用');
            }

            if (!$order || $order['state'] <= 0) {
                $this->error('订单不存在');
            }
            if ($order['verify_expire_time'] > 0 && $order['verify_expire_time'] < time()) {
                $this->error('核销码已过期');
            }

            if (!$goods || $goods['shop_id'] != $goods['shop_id']) {
                $this->error('您不能操作该核销码');
            }

            if ($order['state'] != OderModel::ORDER_STATUS_NO_VERIF) {
                $this->error('当前活动已核销');
            }
            if (in_array($goods['refund_status'], [Goods::REFUND_STATUS_ING, Goods::REFUND_STATUS_GOODS])) {
                $this->error('当前活动正在退款中');
            }
            if (in_array($goods['refund_status'], [Goods::REFUND_STATUS_FINISH, Goods::REFUND_STATUS_FINISH])) {
                $this->error('当前活动已退款');
            }
            // 使用掉核销券
            $order->state = OderModel::ORDER_STATUS_FINISHED;
            $order->verify_time = time();
            $order->verify_user_id = $user['id'];
            $res = $order->save();
            if (!$res) {
                // 一个核销码也没核销
                $this->success('核销失败，无效的核销码');
            }

            controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$goods['actual_payment'], $order['shop']['user_id'], '商户核销订单', 'activity', $order['order_no']);
        });
        
        $this->success('核销成功');
    }
}
